/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.util;

import javax.servlet.http.HttpServletRequest;

import static org.vacoor.nothing.common.util.StringUtils.trimToEmpty;
import static org.vacoor.nothing.common.util.StringUtils.trimToNull;

/**
 * @author vacoor
 */
public abstract class Servlets {

    /**
     * 判断请求的 servlet 是否为前缀映射
     * <p/>
     * servlet mapping 有两种匹配方式: 前缀匹配和后缀匹配
     * <ul>
     * <li>前缀匹配(eg: /prefix/*) : requestURI=/prefix/decode/b, servlet path: /prefix, path info: /decode/b</li>
     * <li>后缀匹配(eg: *.action) : requestURI=/prefix/decode/b.action, servlet path: /prefix/decode/b.action, path info: null</li>
     * </ul>
     *
     * @param request
     * @return
     */
    public static boolean isPrefixServletMapping(HttpServletRequest request) {
        String pathInfo = trimToNull(request.getPathInfo());
        if (pathInfo != null) {
            return true;
        } else {
            /**
             * 对于前缀匹配 /prefix, 当 requestURI = /prefix 时, pathInfo 也为null
             * 此时通过 servletPath 是否是后缀匹配判断
             */
            String servletPath = trimToEmpty(request.getServletPath());
            int index = servletPath.lastIndexOf("/");

            return servletPath.indexOf(".", index + 1) < 0;
        }
    }

    private Servlets() {
    }
}
